<template>
  <a-card class="general-card" title="分销设置">
    <a-form ref="formRef" style="padding: 30px" :model="form">
      <a-divider orientation="left">分销设置</a-divider>
      <a-form-item
        field="isOpen"
        label="是否开启分销"
        :rules="[REQUIRED, VARCHAR20]"
        extra="开启分销，则全店商品具有分销功能"
      >
        <a-switch v-model="form.isOpen">
          <template #checked> 开启 </template>
          <template #unchecked> 关闭 </template>
        </a-switch>
      </a-form-item>
      <a-form-item
        field="commission"
        label="一级佣金比例"
        :rules="[REQUIRED, VARCHAR20]"
      >
        <a-input-number
          v-model="form.commission"
          :style="{ width: '320px' }"
          :min="0"
          :max="99999"
        />
      </a-form-item>
      <a-form-item
        field="secondaryCommission"
        label="二级分佣比例"
        :rules="[REQUIRED, VARCHAR20]"
      >
        <a-input-number
          v-model="form.secondaryCommission"
          :style="{ width: '320px' }"
          :min="0"
          :max="99999"
        />
      </a-form-item>
      <a-button
        style="width: 120px; margin: 30px 220px"
        type="primary"
        @click="handleSubmit"
        >保存</a-button
      >
    </a-form>
  </a-card>
</template>

<script setup lang="ts">
  import {
    getDistributionSetting,
    saveDistributionSetting,
  } from '@/api/promotion';
  import { ref, onMounted } from 'vue';
  import { VARCHAR255, REQUIRED, VARCHAR20 } from '@/utils/validator';
  import { Message } from '@arco-design/web-vue';

  interface formInterface {
    isOpen: boolean;
    secondaryCommission: number;
    commission: number;
  }
  // 数据集
  const form = ref<formInterface>({
    isOpen: true,
    secondaryCommission: 0,
    commission: 0,
    // 表单提交数据
  });

  async function init() {
    const res = await getDistributionSetting();
    if(res.data.success && res.data.result){
      form.value = res.data.result;
    }
  }
  const handleSubmit = async () => {
    console.log(form.value, 'form.value');
    const result = await saveDistributionSetting(form.value);
    if (result.data.success) {
      Message.success('设置成功!');
      init();
    }
  };

  onMounted(() => {
    init();
  });
</script>
